import React, { useState, useRef } from 'react'
import { Todo } from '../App'
import { FaEdit, FaTrash } from 'react-icons/fa'
import { useDispatch } from 'react-redux'
import { toggleTodo, deleteTodo, startEditTodo } from '../store/todoSlice'

// 单个待办事项组件，包含完成、编辑、删除、更多操作菜单
interface Props {
  todo: Todo
}

const TodoItem: React.FC<Props> = ({ todo }) => {
  const dispatch = useDispatch()
  // showActions: 控制更多操作菜单显示
  const [showActions, setShowActions] = useState(false)
  // actionsRef: 用于点击外部关闭菜单
  const actionsRef = useRef<HTMLDivElement>(null)

  React.useEffect(() => {
    if (!showActions) return
    const handleClick = (e: MouseEvent) => {
      if (actionsRef.current && !actionsRef.current.contains(e.target as Node)) {
        setShowActions(false)
      }
    }
    document.addEventListener('mousedown', handleClick)
    return () => document.removeEventListener('mousedown', handleClick)
  }, [showActions])

  return (
    <div className="todo-item">
      <input
        type="checkbox"
        checked={todo.completed}
        onChange={() => dispatch(toggleTodo(todo.id))}
      />
      <span
        className={todo.completed ? 'completed' : ''}
      >
        {todo.text}
      </span>
      <button className="more" onClick={() => setShowActions(v => !v)} title="更多操作">...</button>
      {showActions && (
        <div className={`actions${showActions ? ' show' : ''}`} ref={actionsRef}>
          <button onClick={() => { dispatch(startEditTodo({ id: todo.id, text: todo.text })); setShowActions(false); }}>
            <span style={{ marginRight: 8, verticalAlign: 'middle' }}><FaEdit /></span>编辑
          </button>
          <button onClick={() => { setShowActions(false); dispatch(deleteTodo(todo.id)) }}>
            <span style={{ marginRight: 8, verticalAlign: 'middle' }}><FaTrash /></span>删除
          </button>
        </div>
      )}
    </div>
  )
}

export default TodoItem